local Player = require "agents.player"
local proto_manager = require "common.proto_manager"
local watchdog_proxy = require "agents.watchdog_proxy"
local login_manager = require "agents.login_manager"

local player_manager = {}

local players = {}
local fds = {}

function player_manager.getPlayerByOpenID(openid)
    return players[openid] or nil
end

function player_manager.getPlayerByFd(fd)
    fd = tonumber(fd) or 0
    local openid = fds[fd]
    return openid and player_manager.getPlayerByOpenID(openid) or nil
end

function player_manager.addPlayer(openid,client)
    local player = Player:new(openid,client)
    players[openid] = player
    fds[client:getFd()] = openid
    return player
end

function player_manager.removePlayer(openid)
    local player = player_manager.getPlayerByOpenID(openid)
    players[openid] = nil
    local client = player and player:getClient() or nil
    if client then
        fds[client:getFd()] = nil
    end
end

function player_manager.foreach(func)
    for k,v in pairs(players) do
        func(k,v)
    end
end

function player_manager.clearAll()
    players = {}
    fds = {}
end

function player_manager.online(player,new_client)
    if not player:isOffline() then
        local logout = {
            result = proto_manager.errcode("ErrorCode_AnotherLogined"),
        }
        player:sendMessage("MessageId_LogoutResp","MessageLogoutResp",logout)
    end
    local client = player and player:getClient() or nil
    if client then
        fds[client:getFd()] = nil
        login_manager.removeClient(client:getFd())
        watchdog_proxy.disconnect(client:getFd())
    end
    player:onOnline(new_client)
    fds[new_client:getFd()] = player:getOpenID()
end

return player_manager